package com.witmore.neutron.ai.mcp.server.other;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Description: WeatherService
 * Author: 豆子高
 * Date: 2025/7/2 10:36
 */
@Slf4j
@Service
public class WeatherServer {


    /**
     * HZ-通讯秘钥
     */
    private final static String HZ_API_KEY = "b2a487cdf7b6f5f47e7c97443b41e623";

    /**
     * HZ-账号ID
     */
    private final static String HZ_API_ID = "10005728";

    /**
     * HZ-使用域名接口地址
     */
    private static final String HZ_API_URL = "https://cn.apihz.cn/api/tianqi/tqyb.php";

    private static final ObjectMapper HZ_objectMapper = new ObjectMapper();


    @Tool(description = "根据省份和城市名称获取天气数据，示例：北京 朝阳")
    public WeatherResponse getWeatherTool(@ToolParam(description = "省份名称 如 上海 浙江") String sheng,
                                          @ToolParam(description = "市区名称 如 上海 杭州") String place,
                                          @ToolParam(required = false,description = "要咨询天气的地区ip") String uip) {
        WeatherRequest request = new WeatherRequest(sheng, place, uip);
        log.info("[WeatherService] getWeatherTool city: {}", request);
        return weatherHz(request);
    }


    /**
     * 接口盒子天气查询接口
     * 天气预报API：https://www.apihz.cn/user/index.php
     */
    public WeatherResponse weatherHz(WeatherRequest request) {
        try {
            WeatherResponse response = getWeather(request);
            if (response.isSuccess()) {
                return response;
            } else {
                return new WeatherResponse(response.code, "天气信息查询失败", null, null, null, null, null, null, null, null, null, null, null, null);

            }
        } catch (IOException e) {
            log.error("Error while fetching weather data: {}", e.getMessage());
        }
        return new WeatherResponse(0, "天气信息查询失败", null, null, null, null, null, null, null, null, null, null, null, null);
    }

    /**
     * 获取天气数据
     *
     * @param request 请求参数
     * @return WeatherResponse 天气响应数据
     * @throws IOException 网络或API错误
     */
    public WeatherResponse getWeather(WeatherRequest request) throws IOException {
        // 构建完整URL
        String urlStr = HZ_API_URL + "?id=" + HZ_API_ID + "&key=" + HZ_API_KEY + "&" + request.toQueryString();

        // 创建HTTP连接
        HttpURLConnection connection = (HttpURLConnection) new URL(urlStr).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        // 检查响应状态
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP请求失败，状态码: " + responseCode);
        }

        // 读取响应内容
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            // 解析JSON响应
            return HZ_objectMapper.readValue(response.toString(), WeatherResponse.class);
        } finally {
            connection.disconnect();
        }
    }


    public record WeatherRequest(String sheng, String place, String uip) {
        // 转换为URL参数字符串
        public String toQueryString() {
            StringBuilder sb = new StringBuilder();
            sb.append("sheng=").append(URLEncoder.encode(sheng, StandardCharsets.UTF_8));
            sb.append("&place=").append(URLEncoder.encode(place, StandardCharsets.UTF_8));
            if (uip != null && !uip.isEmpty()) {
                sb.append("&uip=").append(uip);
            }
            return sb.toString();
        }
    }


    /**
     * 天气预报API响应记录
     *
     * @param code                状态码(200成功，400错误)
     * @param msg                 消息内容(错误时返回错误信息)
     * @param precipitation       降水量
     * @param temperature         温度
     * @param pressure            气压
     * @param humidity            湿度
     * @param windDirection       风向
     * @param windDirectionDegree 风向度
     * @param windSpeed           风速
     * @param windScale           风速描述
     * @param place               查询到的地区
     * @param weather1            当日天气1(如"晴转多云"中的"晴")
     * @param weather2            当日天气2(如"晴转多云"中的"多云")
     */
    public record WeatherResponse(
            @JsonProperty("code") int code,
            @JsonProperty("msg") String msg,
            @JsonProperty("precipitation") String precipitation,
            @JsonProperty("temperature") String temperature,
            @JsonProperty("pressure") String pressure,
            @JsonProperty("humidity") String humidity,
            @JsonProperty("windDirection") String windDirection,
            @JsonProperty("windDirectionDegree") String windDirectionDegree,
            @JsonProperty("windSpeed") String windSpeed,
            @JsonProperty("windScale") String windScale,
            @JsonProperty("place") String place,
            @JsonProperty("weather1") String weather1,
            @JsonProperty("weather2") String weather2,
            @JsonProperty("feelst") String feelst
    ) {


        /**
         * 检查请求是否成功
         *
         * @return 如果code为200返回true
         */
        public boolean isSuccess() {
            return code == 200;
        }

        public String fail() {
            if (!isSuccess()) {
                log.error("天气查询失败: {}", msg);
                return "天气信息查询失败";
            }
            return null;
        }

        /**
         * 获取完整天气描述
         *
         * @return 如"晴转多云"
         */
        public String getFullWeather() {
            return weather1 + "转" + weather2;
        }

        /**
         * 获取完整风向风速描述
         *
         * @return 如"东南风 3级"
         */
        public String getFullWindInfo() {
            return windDirection + " " + windScale;
        }

        @Override
        public String toString() {
            return "WeatherResponse{" +
                    "code=" + code +
                    ", msg='" + msg + '\'' +
                    ", precipitation='" + precipitation + '\'' +
                    ", temperature='" + temperature + '\'' +
                    ", pressure='" + pressure + '\'' +
                    ", humidity='" + humidity + '\'' +
                    ", windDirection='" + windDirection + '\'' +
                    ", windDirectionDegree='" + windDirectionDegree + '\'' +
                    ", windSpeed='" + windSpeed + '\'' +
                    ", windScale='" + windScale + '\'' +
                    ", place='" + place + '\'' +
                    ", weather1='" + weather1 + '\'' +
                    ", weather2='" + weather2 + '\'' +
                    '}';
        }
    }


}
